import router from '@/router'

const state = {
  cacheTags: [],
  tabList: [],
  route: null // 存储路由对象
}

const mutations = {
  SET_CACHE_TAGS: (state, data) => {
    state.cacheTags = data || []
  },
  SET_TABS: (state, data) => {
    state.tabList = data || []
  },
  ADD_TABS: (state, data) => {
    const { routeName = '' } = data
    if (routeName === 'Home') {
      state.tabList.unshift(data)
    } else {
      state.tabList.push(data)
    }
  },
  REMOVE_TABS: (state, data) => {
    const { targetPath = '' } = data
    const currentRoute = state.route
    let activeFullPath = currentRoute.fullPath
    if (activeFullPath === targetPath) {
      state.tabList.forEach((tab, index) => {
        if (tab.name === targetPath) {
          const nextTab = state.tabList[index + 1] || state.tabList[index - 1]
          if (nextTab) {
            activeFullPath = nextTab.name
          }
        }
      })
    }
    state.tabList = state.tabList.filter((tab) => tab.name !== targetPath)
    if (!state.tabList.length || !state.tabList.length) {
      activeFullPath = '/home'
    }
    router.push({ path: activeFullPath })
  },
  UPDATE_ROUTE(state, newRoute) {
    state.route = newRoute
  },
  CLOSE_TABS(state, toPath) {
    const currentRoute = state.route
    const activeFullPath = currentRoute.fullPath
    state.tabList = state.tabList.filter((tab) => tab.name !== activeFullPath)
    router.push({ path: toPath || '/home' })
  },
  CLOSE_OTHER_TABS(state, { curTabPath, tabActive }) {
    state.tabList = state.tabList.filter((i) => i.name === curTabPath)
    if (curTabPath === tabActive) return
    router.push({ path: curTabPath })
  }
}

const actions = {
  setCacheTags({ commit }, data) {
    commit('SET_CACHE_TAGS', data)
  },
  // 设置 tabs
  setTabs({ commit }, data) {
    commit('SET_TABS', data)
  },
  // 添加 tab
  addTabs({ commit }, data) {
    commit('ADD_TABS', data)
  },
  // 移除Tabs
  removeTabs({ commit }, targetPath) {
    commit('REMOVE_TABS', { targetPath })
  },
  // 关闭页签
  closeTabs({ commit }, toPath) {
    commit('CLOSE_TABS', toPath)
  },
  // 存储路由对象
  updateRoute({ commit }, route) {
    commit('UPDATE_ROUTE', route)
  },
  // 关闭其他 tabs
  closeOther({ commit }, data) {
    commit('CLOSE_OTHER_TABS', data)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
